<?php
namespace app\msg\controller;

use think\Controller;
use extra\Constant;
use think\Log;
use think\cache\driver\Redis;
use think\Config;

class Base extends Controller
{

    protected $appConfig = array();
    protected $cache_db = NULL;
    public $head = 0;       // 请求头
    public $data = array();    // 请求体
    protected $uid = '';
    protected $requestURI = '';

    private $getTokenURI = array(
    );

    protected $filterUrl = array(
    );
    protected $noTokenUrl = array(

    );
    protected $preVersion = array(
    );



   public function __construct()
   {
       parent::__construct();
       $post_contents = file_get_contents("php://input");
       Log::write('tianshenjr/msg/controller/Base.php:上行数据'.$post_contents);
       $json_data = isset($post_contents) ? json_decode($post_contents, true) : null;
       //判断请求方法、HTTP包是否为空
       if (!$json_data || empty($json_data)) {
           if ($this->requestURI == '') {
               $this->_dieAjax("neither POST nor GET", "neither POST nor GET");
           } else {
               $this->_dieAjax("no content", "no content");
           }
       }

       if (!is_array($json_data)) {
           // 解析HEAD失败
           $this->_dieAjax("wrong json format", "wrong json format");
       }
    
      
       
       $this->head = $json_data; // 协议头
       $this->data = isset($json_data['data']) ? $json_data['data'] : array();
       $this->cache_db = new Redis(Config::get('redis'));
    
    
       // 验证数据签名
       $this->validateSign();
       
       unset($this->head['data']);
       unset($json_data);
       
   }


   private function  validateSign()
   {
       if (!(isset($this->data['no_need_sign']) && $this->data['no_need_sign'])) {
           if (!isset($this->data['sign']) || !($this->data['sign'])) {

               $this->_dieAjax('data: ' . json_encode($this->data), 'no sign');
           }

//           $partner_id = $this->head['partner_id'];
           $secret_key = Constant::SECRET_KEY;
//           if($partner_id != '') {
//               $params = C();
//               $partner_conf = $params['PARTNER_ID_LIST'];
//               $secret_key = $partner_conf[$partner_id];
//           }

           $md5 = gen_sign($this->data, $secret_key);
           if (strtolower($this->data['sign']) !== $md5) {
               
               //测试用，快速开发，开发完放开sign检验
               if(isset($this->data['testSign']) && $this->data['testSign']=='no'){
                   //$this->_dieAjax("正确的sign: ".$md5, 'wrong sign');
               }else{
                   $this->_dieAjax("正确的sign: ".$md5, 'wrong sign');
               }
           }
       }
   }


    private function _dieAjax($tips='', $msg, $code=-1){
        die(json_encode(array('code' => $code, 'msg' => $msg)));
    }
    
   
}
